package com.sunshine.lnuplus.service

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.os.Looper
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.RemoteViews
import android.widget.RemoteViewsService
import android.widget.TextView
import androidx.appcompat.view.menu.ActionMenuItemView
import androidx.cardview.widget.CardView
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.model.LessonBean
import com.sunshine.lnuplus.model.WidgetData
import com.sunshine.lnuplus.utils.ColorUtils
import com.sunshine.lnuplus.utils.DateUtils
import com.sunshine.lnuplus.view.LessonLayout
import es.dmoral.toasty.Toasty
import java.util.*
import kotlin.Comparator
import kotlin.collections.ArrayList

class UpdateWidgetService : RemoteViewsService() {

    override fun onGetViewFactory(intent: Intent?): RemoteViewsFactory {
        return ListRemoteViewsFactory(this, intent)
    }

    inner class ListRemoteViewsFactory(
        private val mContext: Context,
        private val intent: Intent?
    ) : RemoteViewsFactory {

        override fun onCreate() {}
        override fun onDestroy() {}
        override fun getCount(): Int {
            return 1
        }

        override fun getViewAt(position: Int): RemoteViews {
            val lessonView = RemoteViews(mContext.packageName, R.layout.item_widget_timetable)
            val intentClick = Intent()
            lessonView.setOnClickFillInIntent(R.id.imageView_timetable, intentClick)

            try {
                if (WidgetData.lessonList == null || WidgetData.widgetStyle == null){
                    WidgetData.initData(mContext)
                    WidgetData.initTimetableView(mContext)
                }
                println("widgetchange")
                lessonView.setImageViewBitmap(R.id.imageView_timetable, WidgetData.lessonBitmap)
            }catch (e: Exception){
                Looper.prepare()
                Toasty.error(mContext, "$e 添加小部件失败").show()
                Looper.loop()
            }

            return lessonView
        }

        override fun onDataSetChanged() {
        }

        override fun getLoadingView(): RemoteViews? {
            return null
        }

        override fun getViewTypeCount(): Int {
            return 1
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun hasStableIds(): Boolean {
            return true
        }
    }
}